package com.wyj.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyChatServer {
    private String host;
    private int port;

    public NettyChatServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        //1、创建bossGroup线程组，处理连接事件。默认线程数为2*处理器线程数
        NioEventLoopGroup bossGroup = null;
        //    2、创建workGroup线程组，处理读写事件。默认线程组数量为2*处理器线程数
        NioEventLoopGroup workerGroup = null;
        try {
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            //    3、创建服务端启动助手
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //    4、设置启动助手
            serverBootstrap.group(bossGroup, workerGroup)
                    //5、设置服务端通道的实现类
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    //6、设置服务端队列的线程数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //7、设置活跃状态.child设置的workerGroup中的线程
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    //8、创建一个通道初始化对
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //    9、向pipeline添加自定义的处理类
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new NettyChatServerHandler());

                        }
                    });
            //    10、启动服务端并且绑定端口，同时将异步操作改为同步 .sync()
            ChannelFuture channelFuture = serverBootstrap.bind(host, port);
            channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
                if (channelFuture1.isSuccess()) {
                    System.out.println("【端口绑定启动成功】");
                } else {
                    System.out.println("【端口绑定失败了】");
                }
            });
            System.out.println("【服务端启动成功】");
            //    11、关闭通道和关闭连接池。并不是真正意义上的关闭，而是监听通道关闭状态。
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bossGroup && null != workerGroup) {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }

    }

    public static void main(String[] args) {
        new NettyChatServer("127.0.0.1",19999).run();
    }
}
